<?php

class YTGdataApi {
	
	private $api_key;
	private $url;
	private $start_index;
	private $max_results;
	
	private function __construct($key){
		$this->api_key= $key;
		$this->url = "http://gdata.youtube.com/feeds/api/videos";
		$this->start_index=1;
		$this->max_results=5;	
	}
	
	public static function getInstance($key){
		return new self($key);
	}
	
	private function makeRequest($methodParamArray = array() ){
		$paramArray = array("key" => $this->api_key, "alt" => "atom", "v" => "2");
		$paramArray =  array_merge($paramArray,$methodParamArray);
		$resultat = Outils_Connexion::curl_get($this->url,$paramArray);
		return $this->getXMLResult($resultat);
	}
	
	private function getXMLResult($str){
		$xml =  simplexml_load_string($str);
		if (! $xml->error){
			return $xml;
		} else {
			throw new Exception($xml->error->domain);
		}
	}
	
	public function getYtVideos($query){
			$xml = $this->makeRequest(array("max-results" => $this->max_results, "start-index" => $this->start_index, "category" => "Music", "format" => "5", "q"=> $query) );
			$html = "";
			// pas besoin de urlencode($query) car addslashes($cle) fait dans la classe Recherche
			foreach($xml->entry as $entry){
				$ytId = $this->getYtId($entry);
				
				$media = $entry->children('http://search.yahoo.com/mrss/');
				
				$title = $media->group->title;
				$tabTitle = explode("-",$title,2);
				Outils_Chaines::htmlEncodeArray($tabTitle);
				if (sizeof($tabTitle)>=2){
					$artist = htmlspecialchars(trim($tabTitle[0]),ENT_QUOTES,"UTF-8");
					$trackTitle =  htmlspecialchars(trim($tabTitle[1]),ENT_QUOTES,"UTF-8");
				} else {
					$artist = "";
					$trackTitle =  htmlspecialchars($title,ENT_QUOTES,"UTF-8");
				}
				
				$thumbnailUrl = $this->getThumbnailUrl($media);
				
				$length = $this->getVideoLength($media);
				
				$viewCount = $this->getVideoViewCount($entry);
      
				$rating = $this->getVideoRating($entry);
				
				// Test si la vidéo est déjà dans la Bd
				$titleObj = Title_Bd::checkIfVideo($ytId);
				$videoExist =  $titleObj !==false ? true : false ;
				
				if ($videoExist){
					$className = "titleL";
					$inputs =<<<EOT
					<input type="hidden" value="{$titleObj->getIdTitle()}" class="idTitle">
EOT;
				}else {
					$className = "titleL_yt";
					$inputs = <<<EOT
						<input type="hidden" class="yt_artist" name="artist" value="{$artist}"/>
						<input type="hidden" class="yt_title" name="name" value="{$trackTitle}"/>
						<input type="hidden" class="yt_youtube_id" name="youtube_id" value="{$ytId}"/>
EOT;
				}
				
      
      			$html.=<<<EOT
				
					<div class="titleYT {$className}">
						{$inputs}
						<figure>
							<img src="{$thumbnailUrl}" alt="Img {$title}"/>
						</figure>
						<div>
							<p class="ytname">{$title}</p>
							<span class="ytlength">{$length}</span>
								<p class="ytview">{$viewCount} vues</p>
								<p class="ytrating">noté {$rating}/5 par les utilisateurs de YT</p>
						</div>
						<div class="clearer"></div>
					</div>

EOT;

			}
			
			$html .= $this->makePagination();
			
			return $html;


	}

				
	private function getYtId($entry){
		$fullId= (string) $entry->id;
		$tab = explode(":",$fullId);
		return $tab[sizeof($tab)-1];
	}
	
	private function getThumbnailUrl($media){
		$attrs = $media->group->thumbnail[0]->attributes();
      	$thumbnail = $attrs['url'];
		return $thumbnail;
	}
	
	private function getVideoLength($media){
		// get <yt:duration> node for video length
     	$yt = $media->children('http://gdata.youtube.com/schemas/2007');
      	$attrs = $yt->duration->attributes();
      	return Outils_Date::sec2hms ($attrs['seconds'],true); 
	}
	
	private function getVideoViewCount($entry){
		// get <yt:stats> node for viewer statistics
      	$yt = $entry->children('http://gdata.youtube.com/schemas/2007');
      	$attrs = $yt->statistics->attributes();
      	return $attrs['viewCount']; 
		
	}
	
	private function getVideoRating($entry){
		// get <gd:rating> node for video ratings
		$gd = $entry->children('http://schemas.google.com/g/2005'); 
		if ($gd->rating) {
		$attrs = $gd->rating->attributes();
		$rating = (float) $attrs['average']; 
		$rating = round($rating,2);
		} else {
			$rating = 0; 
		}
		return $rating;
	}
	
	
	private function extraireQuery() {
		$query = $_SERVER['QUERY_STRING'];
		$tabParams = explode('&', $query);
	
		$urlParamTab = array();
		foreach ($tabParams as $param) {
		 	 $tab = explode('=', $param);
		  	// si param existe et != ""
		  	if (isset($tab[1]) && $tab[1] !=""){
		  		$urlParamTab[$tab[0]] = $tab[1];
		  	}
		}

		return $urlParamTab;
	 }

	private function makeUrl($index){
	  $url = "index.php?";
	  $urlParam = $this->extraireQuery();
		  foreach($urlParam as $k=>$v){
			  if($k != 'p' && $k != 'typeP' && $k!= 'blocTarget'){ // param blocTarget ajouté en javascript
			  $url .= "{$k}={$v}&amp;";
			  }
		  }
		  $url .= "typeP=bloc&amp;";
	  $url .= "p={$index}";
	  
	  return $url;
	}
	
	private function makePagination(){
		if ($this->start_index - $this->max_results < 1){
			$bBack = "";
		} else {
			$bBack = "<a href=\"{$this->makeUrl($this->start_index-$this->max_results)}\" class=\"blocP\"> &lt;&lt; Précédent </a>";
		}
		$bNext = "<a href=\"{$this->makeUrl($this->max_results+$this->start_index)}\" class=\"blocP\"> Suivant &gt;&gt;</a>";
		$html = "<div class=\"links\">{$bBack} {$bNext}</div>";
		
		return $html;
	}
	
	public function setStartIndex($v){
		$this->start_index = $v;	
	}
	
	
}


?>